package com.surfilter.mq.threadman;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadExecuteManager implements ThreadManager{
	
	private static final Logger logger = LoggerFactory.getLogger(ThreadExecuteManager.class);
	
	private ScheduledExecutorService pools;
	
	private Integer thread_num = 0;
	
	private Integer current_thread_num = 1;
	
	private int thread_exe_timeout;
	
	private ScheduledExecutorService clear_service; 
	
	public ThreadExecuteManager(int thread_num) {
		super();
		current_thread_num = thread_num;
		pools = Executors.newScheduledThreadPool(thread_num);
	}
	
	public ThreadExecuteManager(int thread_num, int thread_exe_timeout) {
		this(thread_num);
		this.thread_exe_timeout = thread_exe_timeout;
		startClearService();
	}
	
	public void startClearService(){
		clear_service = Executors.newSingleThreadScheduledExecutor();
		Runnable runnable = new Runnable() {  
            public void run() {  
                // task to run goes here
            }
		};
		clear_service.scheduleAtFixedRate(runnable, 10, 10, TimeUnit.SECONDS);
	}
	
	public void execute(Runnable runnable){
		try{
			while(true){
				int thread_user_num = getThreadNum();
				if(thread_user_num >= current_thread_num){
					Thread.sleep(1);
					continue;
				}
				addThreadAndStart(runnable);
				break;
			}
		}catch(Exception e){
			logger.error("分配线程异常:", e);
		}
	}
	
	public void addThreadAndStart(Runnable runnable){
		synchronized(thread_num){
			pools.execute(runnable);
			thread_num ++;
		}
	}
	
	public void remove(String thread_name){
		synchronized(thread_num){
			thread_num --;
		}
	}
	
	public int getThread_num() {
		return thread_num;
	}

	public void setThread_num(int thread_num) {
		this.thread_num = thread_num;
	}
	
	public int getThreadNum(){
		return thread_num;
	}

	@Override
	public void executes(List<Runnable> runnables) {
		// TODO Auto-generated method stub
		
	}
}
